package com.zegome.game.me;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Vector;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Button.ButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton.ImageButtonStyle;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Label.LabelStyle;
import com.badlogic.gdx.scenes.scene2d.ui.ScrollPane;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.utils.ChangeListener;
import com.badlogic.gdx.scenes.scene2d.utils.TextureRegionDrawable;
import com.zegome.game.main.AndroidGameController;
import com.zegome.game.main.ZegomeActivity;

public class AutoRunText extends Actor {

	// ===========================================================
	// Constants
	// ===========================================================
	public static final String els_url = "http://zegome.com/service/index/";
	public static final String els_url_resource = "http://zegome.com/service/";

	// ===========================================================
	// Fields
	// ===========================================================
	public DefaultHttpClient httpClient;

	Vector<GameAdvertise> gameAdvertiseLoad = new Vector<GameAdvertise>();

	private int x, y, wi, hi;
	private int stateNotify;
	private int scrollX;
	private int cursor;
	private float timeWaitNotify;
	private float timeWaitRunAgain;

	public boolean isCheckNotifyAnonymous;
	public boolean isSendingCheckNotifyAnonymous;

	public boolean isLastestVersion = true;
	public boolean isHasAccount = false;
	public boolean isNetWorkAvaiable = true;
	public boolean isVietnamese;
	public boolean isLoadingGameAdvertise;

//	public GameScreen screen;
	AsyncTaskNotify android;
	public ScrollPane scroll;
	private Label label;
	public Image image;
	public ImageButton button;
	private String link;
	public Vector<NotifyItem> notify;
	private String text;
	private String imgPath;
	private BitmapFont font;
	Texture icon;

	// ===========================================================
	// Constructor
	// ===========================================================
	private ZegomeActivity act;
	private AndroidGameController mController;

	public AutoRunText(final AndroidGameController controller) {
		scroll = new ScrollPane(new Actor());
		notify = new Vector<NotifyItem>();
		cursor = 0;
		image = new Image();
		android = new AsyncTaskNotify();
		httpClient = new DefaultHttpClient();
		mController = controller;
		act = mController.getActivity();
		if(Locale.getDefault().getDisplayLanguage().equals("Tiếng Việt")){			
			isVietnamese = true;
		}
		else{
			isVietnamese = false;
		}
	}

	public void init(Stage stage, Skin skin, BitmapFont font, TextureRegion imageRegion) {
		this.font = font;
//		this.screen = screen;
		if (button == null) {
			final ImageButtonStyle style = new ImageButtonStyle(skin.get("trans", ButtonStyle.class));
			boolean ok = false;
			if (image != null) {
				style.imageUp = new TextureRegionDrawable(imageRegion);
				style.imageUp.setMinWidth(wi);
				style.imageUp.setMinHeight(hi);
				ok = true;
			}
			if (image != null) {
				style.imageDown = new TextureRegionDrawable(imageRegion);
				style.imageDown.setMinWidth(wi);
				style.imageDown.setMinHeight(hi);
				if (!ok)
					ok = true;
			}
			if (image != null) {
				style.imageDisabled = new TextureRegionDrawable(imageRegion);
				style.imageDisabled.setMinWidth(wi);
				style.imageDisabled.setMinHeight(hi);
				if (!ok)
					ok = true;
			}
			if (!ok) {
				throw new IllegalArgumentException("One of regions must be different from null");
			}
			button = new ImageButton(style);
			button.setPosition(x, y);
			button.addListener(new ChangeListener() {

				@Override
				public void changed(ChangeEvent arg0, Actor arg1) {
					// TODO Auto-generated method stub
					if (link != null) {
						act.postHandler(new Runnable() {

							@Override
							public void run() {
								// TODO Auto-generated method stub
								Intent i = new Intent(Intent.ACTION_VIEW, Uri
										.parse(link));
								act.startActivity(i);
							}
						});

					}
				}
			});
		}
	}
	
	public void show(final Stage stage) {
		stage.addActor(this);
		stage.addActor(scroll);
		stage.addActor(image);
		stage.addActor(button);
	}
	
	public void hide() {
		this.remove();
		scroll.remove();
		image.remove();
		button.remove();
	}
	
	// ===========================================================
	// Getter & Setter
	// ===========================================================
	public void setXY(int x, int y) {
		this.x = x;
		this.y = y;
	}

	public void setWH(int wi, int hi) {
		this.wi = wi;
		this.hi = hi;
	}

	public void addNotify(int type, String content, String image, String link) {
		notify.add(new NotifyItem(content, image, link));
		if (isNetWorkAvaiable) {
			if (type >= 0) {
				android.saveNotify(type, content, link, image);
			}
		} else {
			// ctr.androidHelper.log("ADD NOTIFY OFFLINE "+ content
			// +" -- "+link+" -- "+image);
		}
	}

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================
	@Override
	public void act(float pDeltaTime) {
		// TODO Auto-generated method stub

		if (isNetWorkAvaiable) {
			if (isCheckNotifyAnonymous == false) {
				if (isSendingCheckNotifyAnonymous == false) {
					isSendingCheckNotifyAnonymous = true;
					android.sendGetNotice();
				}
			}
		}

		if (isNetWorkAvaiable) {
			if (gameAdvertiseLoad != null) {
				if (gameAdvertiseLoad.size() != 0) {
					if (isLoadingGameAdvertise == false) {
						for (int i = 0; i < gameAdvertiseLoad.size(); i++) {
							if (gameAdvertiseLoad.elementAt(i).isFinish == false) {
								if (gameAdvertiseLoad.elementAt(i).isSending == false) {
									android.sendGetAdvertise(mController, gameAdvertiseLoad.elementAt(i));
								}
								break;
							}
						}
					}
				}
			}
		}

		if (text == null) {
			if (notify.size() > 0) {
				if (cursor > notify.size() - 1) {
					stateNotify = 5;
					timeWaitRunAgain = 0;
					cursor = 0;
					return;
				}
				text = "                                                                 "
						+ notify.elementAt(cursor).content + "            ";
				imgPath = notify.elementAt(cursor).image;
				link = notify.elementAt(cursor).link;
				scrollX = 0;
				cursor++;
			} else {
				this.setVisible(false);
			}
		}

		if (stateNotify == 5) {
			if (timeWaitRunAgain > 5) {
				stateNotify = 0;
			} else {
				timeWaitRunAgain += pDeltaTime;
			}
			this.setVisible(false);
		}

		if (stateNotify == 0) {
			if (text != null) {
				setTextNotify(text);
			}
		}

		if (this.isVisible() == true) {
			if (scroll.getWidget().getWidth() > 5) {
				if (stateNotify == 2) {

					if (scrollX < scroll.getMaxX()) {
						scroll.setScrollX(scrollX);
						scrollX += 1 * (((pDeltaTime / 0.02f) < 1) ? 1
								: (pDeltaTime / 0.02f));
					} else {
						if (timeWaitNotify > 1) {
							stateNotify = 3;
						} else {
							timeWaitNotify += pDeltaTime;
						}
					}
				} else if (stateNotify == 3) {
					this.setVisible(false);
					image.setVisible(false);
					button.setVisible(false);
					stateNotify = 0;
					timeWaitNotify = 0;
					text = null;
					scrollX = 0;
				}
			}
		}
		super.act(pDeltaTime);
	}

	// ===========================================================
	// Methods
	// ===========================================================
	private void setTextNotify(String text) {
		if (label == null) {
			LabelStyle style = new LabelStyle(font, Color.WHITE);
			label = new Label("", style);
			scroll.setWidget(label);
		}
		if (imgPath != null) {
			if (icon != null) {
				icon.dispose();
			}
			icon = new Texture(Gdx.files.external(imgPath));
			icon.setFilter(TextureFilter.Linear, TextureFilter.Linear);
			TextureRegion iconRg = new TextureRegion(icon);
			if (image == null) {
				// image = ctr.stageHelper.createImage(icon, x, y, 40, 40);
			} else {
				image.setDrawable(new TextureRegionDrawable(iconRg));
				image.setPosition(x + 600 - 64, y);
				image.setSize(64, 64);
			}
			image.setVisible(true);
			button.setVisible(true);
		} else {
			if (image != null) {
				image.setVisible(false);
			}
			button.setVisible(false);
		}
		label.setText(text);
		scroll.setBounds((x), (y), (wi), (hi));
		scroll.setSmoothScrolling(false);
		scroll.setScrollingDisabled(false, true);

		scroll.setY(y);
		scroll.setScrollX(0);
		timeWaitNotify = 0;
		stateNotify = 2;
		this.setVisible(true);
	}

	// ===========================================================
	// Inner and Anonymous Classes
	// ==========================================================
	class AsyncTaskNotify {

		public String convertStreamToString(InputStream is) {

			BufferedReader reader = new BufferedReader(
					new InputStreamReader(is));
			StringBuilder sb = new StringBuilder();

			String line = null;
			try {
				while ((line = reader.readLine()) != null) {
					sb.append(line + "\n");
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			return sb.toString();
		}

		public void sendGetNotice() {
			final AsyncTaskNetWork net = new AsyncTaskNetWork(httpClient,
					new INetWorkAction() {

						@Override
						public String send() {
							// TODO Auto-generated method stub
							String responseText = null;
							final HttpPost httpost = new HttpPost(els_url
									+ "get-notice");

							List<NameValuePair> nvps = new ArrayList<NameValuePair>();
							nvps.add(new BasicNameValuePair("game_id", "1"));
							nvps.add(new BasicNameValuePair("platform", "1"));

							try {
								httpost.setEntity(new UrlEncodedFormEntity(
										nvps, HTTP.UTF_8));
							} catch (Exception ex) {
							}
							HttpResponse response = null;
							try {
								response = httpClient.execute(httpost);
							} catch (Exception e) {
								// TODO Auto-generated catch block
								// e.printStackTrace();
							}
							if (response == null) {
								// ctr.stageHelper.createDialog(stage,
								// tweenManager, "Lối kết nối!", 1, null, null);
								return null;
							}

							int status_code = response.getStatusLine()
									.getStatusCode();
							// log("" + status_code);
							HttpEntity entity = response.getEntity();
							if (entity != null || status_code == 200
									|| status_code == 201) {
								InputStream instream = null;
								try {
									instream = entity.getContent();
								} catch (IllegalStateException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}

								responseText = convertStreamToString(instream);

								// Closing the input stream will trigger
								// connection release
								try {
									instream.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
							}
							Log.e("ZeGome", "Response Get Notify Anonymous: "
									+ responseText);
							return responseText;
						}

						@Override
						public void receive(String responseText) {
							// TODO Auto-generated method stub
							if (responseText == null) {
								isSendingCheckNotifyAnonymous = false;
								return;
							}
							saveFile("notify", "");
							isCheckNotifyAnonymous = true;
							isSendingCheckNotifyAnonymous = false;
							try {
								JSONObject result = new JSONObject(responseText);
								if (result.getString("code").equals("1")) {
									JSONObject content = result
											.getJSONObject("content");
									JSONArray messages = content
											.getJSONArray("message");
									JSONArray advertise = content
											.getJSONArray("advertise");
									notify.removeAllElements();
									gameAdvertiseLoad.removeAllElements();
									for (int i = 0; i < messages.length(); i++) {
										JSONObject ele = messages
												.getJSONObject(i);
										addNotify(0,isVietnamese ? ele.getString("message_content")
														: ele.getString("message_eng"), null, null);
									}

									for (int i = 0; i < advertise.length(); i++) {
										JSONObject ele = advertise
												.getJSONObject(i);
										gameAdvertiseLoad.add(new GameAdvertise(
												i,
												ele.getString("icon"),
												ele.getString("link"),
												isVietnamese ? ele
														.getString("message_vn")
														: ele.getString("message_eng")));
									}
								}
							} catch (Exception ex) {
							}
						}
					});
			act.postHandler(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					net.send();
				}
			});
		}

		public void saveFile(String name, String data) {
			try {
				File wallpaperDirectory = new File(
						Environment.getExternalStorageDirectory()
								+ "/data/ogme/");
				if (!wallpaperDirectory.exists()) {
					wallpaperDirectory.mkdirs();
				}
				File myFile = new File(
						Environment.getExternalStorageDirectory()
								+ "/data/ogme/" + name);
				myFile.createNewFile();
				FileOutputStream fOut = new FileOutputStream(myFile);
				OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
				myOutWriter.append(data);
				myOutWriter.close();
				fOut.close();
			} catch (Exception e) {
			}
		}

		public void saveNotify(int type, String content, String link,
				String path) {
			String current = getStringFile("notify", "");
			current += type + "*" + content + "*" + link + "*" + path + "*"
					+ "#";
			saveFile("notify", current);
		}

		public String getStringFile(String name, String def) {
			String result = def;
			String data = null;
			try {
				File myFile = new File(Environment.getExternalStorageDirectory() + "/data/ogme/" + name);

				FileInputStream fIn = new FileInputStream(myFile);

				BufferedReader myReader = new BufferedReader(
						new InputStreamReader(fIn));
				String aDataRow = "";
				String aBuffer = "";
				while ((aDataRow = myReader.readLine()) != null) {
					aBuffer += aDataRow;
				}
				data = aBuffer;
				myReader.close();
			} catch (Exception e) {
			}
			if (data != null) {
				result = data;
			}
			return result;
		}

		public void sendGetAdvertise(final AndroidGameController controller, final GameAdvertise lazy) {
			isLoadingGameAdvertise = true;
			lazy.isSending = true;
			final AsyncTaskNetWork newNet = new AsyncTaskNetWork(httpClient,
					null);
			newNet.setByteAction(new IByteAsync() {

				@Override
				public byte[] send() {
					byte[] bytes = null;
					try {
						// log(els_url_resource+lazy.link);
						bytes = readBytes(OpenHttpConnection(els_url_resource + lazy.link));
					} catch (Exception e) {
						// log(e.getMessage());
					}
					return bytes;
				}

				@Override
				public void receive(final byte[] bytes) {
					if (bytes == null) {
						lazy.isFinish = false;
						lazy.isSending = false;
						isLoadingGameAdvertise = false;
						return;
					}
					controller.getActivity().postRunnable(new Runnable() {

						@Override
						public void run() {
							try {
								File wallpaperDirectory = new File(Environment.getExternalStorageDirectory()
										+ "/data/avatar/");
								if (!wallpaperDirectory.exists()) {
									wallpaperDirectory.mkdirs();
								}
								FileOutputStream out = new FileOutputStream(Environment.getExternalStorageDirectory()
												+ "/data/avatar/" + lazy.name);

								out.write(bytes);
								out.flush();
								out.close();
								// System.out.println("LOAD OK"+lazy.link);
								addNotify(1, lazy.content, "data/avatar/"
										+ lazy.name, lazy.url);
								lazy.isFinish = true;
								lazy.isSending = false;
								isLoadingGameAdvertise = false;
							} catch (Exception ex) {
								// log(ex.getMessage());
							}
						}
					});
				}

			});

			act.postHandler(new Runnable() {

				@Override
				public void run() {
					// TODO Auto-generated method stub
					newNet.sendByte();
				}
			});
		}

		public byte[] readBytes(InputStream inputStream) {
			// this dynamically extends to take the bytes you read
			if (inputStream == null)
				return null;
			ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

			// this is storage overwritten on each iteration with bytes
			int bufferSize = 1024;
			byte[] buffer = new byte[bufferSize];

			// we need to know how may bytes were read to write them to the
			// byteBuffer
			int len = 0;
			try {
				while ((len = inputStream.read(buffer)) != -1) {
					byteBuffer.write(buffer, 0, len);
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			try {
				inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// and then we can return your byte array.
			return byteBuffer.toByteArray();
		}

		@SuppressWarnings("deprecation")
		private InputStream OpenHttpConnection(String strURL)
				throws IOException {

			InputStream inputStream = null;
			URL url = new URL(strURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			if (Build.VERSION.SDK != null && Build.VERSION.SDK_INT > 13) {
				conn.setRequestProperty("Connection", "close");
			}
			try {
				// conn.setRequestMethod("GET");
				// conn.connect();
				// if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				inputStream = conn.getInputStream();
				// }
				// System.out.println(strURL);
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			return inputStream;

		}

	}
}
